define(['jquery', 'text!../template/map.html', 'css!../css/map', 'common'], function ($, tplMap) {
    let _map = {};
    let currentPage = 1;
    let imgUrl = window.location.host;
    let hd = imgUrl.split('.njdtwise')[0]
    imgUrl = hd == 'www' ? 'http://www.njdtwise.com/images/' : 'http://dev.njdtwise.com/images/';
    let tpls = {
        'tplMap': _.template(tplMap)
    };

    _map.show = function () {
        $('#contant').html(tpls.tplMap());
        Ajax('/xjrest/task/point_task_list', function (result) {
            let mapData = result.ret.value;
            drawMap(mapData);
        });
        $("#mapSelect").change(function (event) {
            let status = $(this).val();
            Ajax('/xjrest/task/point_task_list?status=' + status, function (result) {
                let mapData = result.ret.value;
                drawMap(mapData);
            });
        });
    }

    function drawMap(data) {
        let allpoint = [];
        let mapData = [];
        $.each(data, function (index, el) {
            if (el.longitude != '' && el.latitude != '') {
                mapData.push(el)
            }
        });
        let map = new BMap.Map("allmap");
        map.enableScrollWheelZoom(true);
        let infoWindows = [];
        var markers = [];
        $.each(mapData, function (index, el) {
            allpoint.push({
                "lng": el.longitude,
                "lat": el.latitude
            });
            let pt = new BMap.Point(el.longitude, el.latitude);
            let myIcon;
            if (el.taskStatus == '2') {
                myIcon = new BMap.Icon("./img/map/normal.png", new BMap.Size(30, 30));
            } else if (el.taskStatus == '3') {
                myIcon = new BMap.Icon("./img/map/bad.png", new BMap.Size(25, 25));
            } else if (el.taskStatus == '1') {
                myIcon = new BMap.Icon("./img/map/warn.png", new BMap.Size(30, 30));
            } else if (el.taskStatus == '') {
                myIcon = new BMap.Icon("./img/map/noTask.png", new BMap.Size(25, 25));
            }
            let title = el.taskStatus == '1' ? '待巡检' : el.taskStatus == '2' ? '已巡检' : el.taskStatus == '3' ? '巡检超时' : '暂无任务';
            let marker = new BMap.Marker(pt, {
                icon: myIcon,
                title: el.pointName + ',' + title
            });
            markers.push(marker);

            let _html = `<div style='height:320px;width:320px;border-radius: 5px;overflow:hidden'>
                            <div style='background:#2e91e6;color:#fff;padding:5px;'>
                                <div style='display:flex;justify-content: space-between;margin-bottom: 5px;'>
                                    <span title="${el.pointName}">${truncate(el.pointName,8)}</span>
                                    <div>
                                        <span>负责人:</span>
                                        <span>${el.dealUserName}</span>
                                    </div>
                                </div>
                                <div style='margin-bottom: 5px;'>
                                    <span>当前任务情况:</span>
                                    <span class='lastInfo' id="lastInfo" point="${el.pointId}">暂无任务</span>
                                </div>
                                <div style='margin-bottom: 5px;'>
                                    <span>查看详情:</span>
                                    <button class='found' onclick='mapTable("${el.pointId}","${el.taskStatus}")'>查看</button>
                                </div>
                            </div>
        					<span style="font-size: 0.1rem;" class="uptime">最近巡检上报照片</span>
                            <div class="imgbox">
        					</div>
                        </div>`;
            var infoWindow = new BMap.InfoWindow(_html);
            infoWindows.push(infoWindow);
            markers[index].addEventListener('click', function () {
                markers[index].openInfoWindow(infoWindows[index]);
                let id = $("#lastInfo").attr("point");
                $('.BMap_pop>img').hide();
                Ajax('/xjrest/task/point_lastest_task?pointId=' + id, function (result) {
                    if (result.ret.success) {
                        if (result.ret.taskFlag == 0) {
                            $("#lastInfo").html('暂无任务');
                        } else {
                            if (result.ret.taskInfo.status == 1) {
                                $("#lastInfo").html('待办');
                            } else if (result.ret.taskInfo.status == 2) {
                                if (result.ret.taskInfo.dealStatus == 1) {
                                    $("#lastInfo").html('正常');
                                } else if (result.ret.taskInfo.dealStatus == 2) {
                                    $("#lastInfo").html('待维修');
                                } else if (result.ret.taskInfo.dealStatus == 3) {
                                    $("#lastInfo").html('器材过期');
                                } else if (result.ret.taskInfo.dealStatus == 4) {
                                    $("#lastInfo").html('现场维修');
                                }
                            } else if (result.ret.taskInfo.status == 3) {
                                $("#lastInfo").html('任务超时');
                            }
                        }
                    }
                })
                Ajax('/xjrest/task/point_task_image?pointId=' + id, function (result) {
                    if (result.ret.success) {
                        if (result.ret.value.length) {
                            var imgLength = result.ret.value.length;
                            var listimg = '';
                            for (var i = 0; i < imgLength; i++) {
                                listimg += `<div class="imgcontent">
        										<img onclick='showImg("${imgUrl+result.ret.value[i].filePath}")' src="${imgUrl+result.ret.value[i].filePath}" alt="">
        										<span class="uptime">上报时间:${result.ret.value[i].finishTime}</span>
        									</div>`;
                            }
                            $('.imgbox').html(listimg);
                        }
                    }
                })
            });
            map.addOverlay(marker);
        });
        let view = map.getViewport(eval(allpoint));
        map.centerAndZoom(view.center, view.zoom);
        map.addControl(new BMap.MapTypeControl({
            mapTypes: [BMAP_NORMAL_MAP, BMAP_HYBRID_MAP]
        }));
        map.setMapStyleV2({
            styleJson: [{
                "featureType": "poilabel",
                "elementType": "all",
                "stylers": {
                    "visibility": "off"
                }
            }]
        });
    }

    window.mapTable = function (data, status) {
        currentPage = 1;
        let pointId = data;
        let _html = $("#mapInfo").html();
        $(".mapInfo").html(_html).css('display', 'flex');
        $(".magClose").click(function (event) {
            $(".mapInfo").html('').hide();
        });
        setRouteTable(0, 5, pointId, status);
    }
    window.showImg = function (src) {
        // console.log(src);
        $('.showImgbox').attr('src', src);
        $('.showScaleImg').show();
    }
    window.showScaleImg = function (src) {
        $('.showScaleImg').hide();
    }

    function setRouteTable(from, count, id, status) {
        let url = "/xjrest/task/task_query?pointId=" + id + "&type=1"
        let parms = {
            from: from,
            count: 5
        };
        $('#gridRepairTable').datagrid({
            url: url,
            queryParams: parms,
            width: '100%',
            method: 'get',
            border: false,
            singleSelect: true,
            fitColumns: false,
            scrollbarSize: 0,
            loadMsg: "正在查询,请耐心等待。。。。。。。",
            columns: [
                [{
                        field: 'taskTitle',
                        title: '任务名称',
                        width: status == 2 ? "11%" : "13%",
                        align: 'center',
                        formatter: function (value, row) {
                            return `<span title="${value}">${truncate(value,7)}</span>`;
                        }
                    },
                    {
                        field: 'townName',
                        title: '所属街道',
                        width: status == 2 ? "11%" : "13%",
                        align: 'center',
                        formatter: function (value, row) {
                            return `<span title="${value}">${truncate(value,7)}</span>`;
                        }
                    },
                    {
                        field: 'villageName',
                        title: '所属社区',
                        width: status == 2 ? "11%" : "13%",
                        align: 'center',
                        formatter: function (value, row) {
                            return `<span title="${value}">${truncate(value,7)}</span>`;
                        }
                    },
                    {
                        field: 'pointName',
                        title: '任务地点',
                        width: status == 2 ? "11%" : "12%",
                        align: 'center',
                        formatter: function (value, row) {
                            return `<span title="${value}">${truncate(value,7)}</span>`;
                        }
                    },
                    {
                        field: 'beginTime',
                        title: '开始时间',
                        width: status == 2 ? "11%" : "12%",
                        align: 'center',
                        formatter: function (value, row) {
                            return value.substring(5);
                        }
                    },
                    {
                        field: 'endTime',
                        title: '截止时间',
                        width: status == 2 ? "11%" : "12%",
                        align: 'center',
                        formatter: function (value, row) {
                            return value.substring(5);
                        }
                    },
                    {
                        field: 'finishTime',
                        title: '完成时间',
                        width: status == 2 ? "11%" : "12%",
                        align: 'center',
                        formatter: function (value, row) {
                            if (row.status != 2) {
                                return '未完成';
                            } else {
                                return value.substring(5);
                            }
                        }
                    },
                    {
                        field: 'dealUserName',
                        title: '联系人',
                        width: "11%",
                        align: 'center',
                        hidden: status == 2 ? false : true
                    },
                    {
                        field: 'status',
                        title: '巡检结果',
                        width: status == 2 ? "11%" : "12%",
                        align: 'center',
                        formatter: function (value, row) {
                            let str = '';
                            if (value == 1) {
                                str = '待办';
                            } else if (value == 2) {
                                if (row.dealStatus == 1) {
                                    str = '正常';
                                } else if (row.dealStatus == 2) {
                                    str = '待维修';
                                } else if (row.dealStatus == 3) {
                                    str = '器材过期';
                                } else if (row.dealStatus == 4) {
                                    str = '现场维修';
                                }
                            } else if (value == 3) {
                                str = '超时';
                            }
                            return str;
                        }
                    }
                ]
            ],
            loadFilter: function (data) {
                let _data = data.ret.value;
                let totals = data.ret.total;
                if (totals == 0) {
                    $("#noRecordMessage").show();
                } else {
                    $("#noRecordMessage").hide();
                }
                if (0 == totals % 5) {
                    totalPage = parseInt(totals / 5);
                    if (totalPage == 0) {
                        totalPage = 1;
                    }
                } else {
                    totalPage = parseInt(totals / 5) + 1;
                }
                $('#pagination').paginations({
                    currentPage: currentPage,
                    totalPage: totalPage,
                    callback: function (current) {
                        currentPage = current;
                        current = (current - 1) * 5;
                        setRouteTable(current, 5, id);
                    }
                });
                return _data;
            }
        });
    }
    return _map;
})